package com.zbc.demo.handler;

import com.zbc.demo.controller.AbstractController;
import com.zbc.demo.enums.GlobalExceptionEnum;
import com.zbc.demo.exception.BaseException;
import com.zbc.demo.model.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义全局异常处理器
 *
 * @author 万恶的沫白
 * @date 2021/8/13
 */

@ResponseBody
@ControllerAdvice(basePackageClasses = AbstractController.class)
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class.getName());


    /**
     * 业务异常处理
     *
     * @param request 请求
     * @param e       异常
     * @return 响应内容
     */
    @ExceptionHandler(value = BaseException.class)
    Response<?> handleBaseException(HttpServletRequest request, BaseException e) {
        logger.info("request url :{}, code:{}, msg: {}", request.getRequestURI(), e.getCode(), e.getMessage());
        return new Response<>(e, e.getHttpStatus());
    }


    /**
     * 空指针异常处理
     *
     * @param request 请求
     * @param e       异常
     * @return 响应内容
     */
    @ExceptionHandler(value = NullPointerException.class)
    Response<?> handleNpe(HttpServletRequest request, NullPointerException e) {
        logger.info("request url :{}, npe, msg: {}", request.getRequestURI(), e.getMessage());
        BaseException exception = new BaseException(GlobalExceptionEnum.NULL_POINTER_EXCEPTION);
        return new Response<>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 所有异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response<?> handleException(HttpServletRequest request, Exception e) {
        logger.info("request url :{},  msg: {}", request.getRequestURI(), e.getMessage());
        BaseException exception = GlobalExceptionEnum.INTERNAL_SERVER_ERROR.getException();
        return new Response<>(exception, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
